<template>
  <div class="activity-detail">
    <el-card class="detail-card">
      <!-- 活动基本信息 -->
      <div class="activity-header">
        <el-image :src="activity.image" fit="cover" class="activity-image" />
        <div class="activity-info">
          <h1>{{ activity.title }}</h1>
          <div class="activity-meta">
            <p>
              <el-icon><Calendar /></el-icon>
              {{ activity.date }}
            </p>
            <p>
              <el-icon><Location /></el-icon>
              {{ activity.location }}
            </p>
            <p>
              <el-icon><User /></el-icon>
              已报名: {{ activity.participants }}/{{ activity.maxParticipants }}
            </p>
          </div>
          <div class="activity-tags">
            <el-tag size="small" type="success">{{ activity.type }}</el-tag>
            <el-tag size="small" type="warning">+{{ activity.creditPoints }}信用分</el-tag>
          </div>
        </div>
      </div>

      <!-- 活动详情 -->
      <div class="activity-content">
        <h2>活动详情</h2>
        <div class="content-text" v-html="activity.description"></div>
      </div>

      <!-- 活动规则 -->
      <div class="activity-rules">
        <h2>活动规则</h2>
        <div class="rules-list">
          <div v-for="(rule, index) in activity.rules" :key="index" class="rule-item">
            <el-icon><InfoFilled /></el-icon>
            <span>{{ rule }}</span>
          </div>
        </div>
      </div>

      <!-- 活动流程 -->
      <div class="activity-process">
        <h2>活动流程</h2>
        <el-steps :active="1" finish-status="success">
          <el-step
            v-for="(step, index) in activity.process"
            :key="index"
            :title="step.title"
            :description="step.description"
          />
        </el-steps>
      </div>

      <!-- 参与按钮 -->
      <div class="activity-actions">
        <el-button
          type="primary"
          size="large"
          :disabled="activity.participants >= activity.maxParticipants"
          @click="handleJoin"
        >
          {{ activity.participants >= activity.maxParticipants ? '活动已满' : '立即参与' }}
        </el-button>
      </div>
    </el-card>

    <!-- 参与活动弹窗 -->
    <el-dialog
      v-model="joinDialogVisible"
      :title="activity.title"
      width="500px"
    >
      <!-- 湖水问答 -->
      <template v-if="activity.type === 'quiz'">
        <div class="quiz-container">
          <div v-for="(question, index) in quizQuestions" :key="index" class="question-item">
            <h3>{{ index + 1 }}. {{ question.title }}</h3>
            <el-radio-group v-model="quizAnswers[index]">
              <el-radio
                v-for="option in question.options"
                :key="option.value"
                :label="option.value"
              >
                {{ option.label }}
              </el-radio>
            </el-radio-group>
          </div>
          <div class="quiz-actions">
            <el-button type="primary" @click="submitQuiz">提交答案</el-button>
          </div>
        </div>
      </template>

      <!-- 其他活动 -->
      <template v-else>
        <el-form
          ref="joinFormRef"
          :model="joinForm"
          :rules="joinFormRules"
          label-width="100px"
        >
          <el-form-item label="姓名" prop="name">
            <el-input v-model="joinForm.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="joinForm.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="预约时间" prop="appointmentTime">
            <el-date-picker
              v-model="joinForm.appointmentTime"
              type="datetime"
              placeholder="请选择预约时间"
              :disabled-date="disabledDate"
              :disabled-hours="disabledHours"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="joinForm.remark"
              type="textarea"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="joinDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitJoin">确认参与</el-button>
          </span>
        </template>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Calendar,
  Location,
  User,
  InfoFilled
} from '@element-plus/icons-vue'
import { getActivityDetail, joinActivity, submitQuizAnswer } from '@/api/social'

const route = useRoute()
const router = useRouter()

// 活动详情
const activity = ref({
  id: '',
  title: '',
  image: '',
  date: '',
  location: '',
  participants: 0,
  maxParticipants: 0,
  type: '',
  creditPoints: 0,
  description: '',
  rules: [],
  process: []
})

// 参与活动弹窗
const joinDialogVisible = ref(false)
const joinFormRef = ref(null)
const joinForm = ref({
  name: '',
  phone: '',
  appointmentTime: '',
  remark: ''
})

// 湖水问答
const quizQuestions = ref([
  {
    title: '西湖的水质等级是？',
    options: [
      { label: 'A. 一级', value: 'A' },
      { label: 'B. 二级', value: 'B' },
      { label: 'C. 三级', value: 'C' },
      { label: 'D. 四级', value: 'D' }
    ],
    answer: 'A'
  },
  {
    title: '西湖的主要污染源是？',
    options: [
      { label: 'A. 工业废水', value: 'A' },
      { label: 'B. 生活污水', value: 'B' },
      { label: 'C. 农业面源污染', value: 'C' },
      { label: 'D. 以上都是', value: 'D' }
    ],
    answer: 'D'
  },
  {
    title: '西湖的保护措施不包括？',
    options: [
      { label: 'A. 生态修复', value: 'A' },
      { label: 'B. 水质监测', value: 'B' },
      { label: 'C. 工业排放', value: 'C' },
      { label: 'D. 环境教育', value: 'D' }
    ],
    answer: 'C'
  }
])
const quizAnswers = ref([])

// 表单验证规则
const joinFormRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  appointmentTime: [
    { required: true, message: '请选择预约时间', trigger: 'change' }
  ]
}

// 方法
const loadActivityDetail = async () => {
  try {
    const response = await getActivityDetail(route.params.id)
    activity.value = response.data
  } catch (error) {
    ElMessage.error('获取活动详情失败')
  }
}

const handleJoin = () => {
  if (activity.value.type === 'quiz') {
    quizAnswers.value = []
  } else {
    joinForm.value = {
      name: '',
      phone: '',
      appointmentTime: '',
      remark: ''
    }
  }
  joinDialogVisible.value = true
}

const submitJoin = async () => {
  if (!joinFormRef.value) return
  
  await joinFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await joinActivity({
          activityId: activity.value.id,
          ...joinForm.value
        })
        ElMessage.success('报名成功')
        joinDialogVisible.value = false
        loadActivityDetail()
      } catch (error) {
        ElMessage.error('报名失败')
      }
    }
  })
}

const submitQuiz = async () => {
  if (quizAnswers.value.length !== quizQuestions.value.length) {
    ElMessage.warning('请完成所有题目')
    return
  }

  try {
    const score = calculateQuizScore()
    const response = await submitQuizAnswer({
      activityId: activity.value.id,
      answers: quizAnswers.value,
      score
    })

    if (score >= 70) {
      ElMessage.success(`答题成功，得分：${score}，获得${activity.value.creditPoints}信用分`)
    } else {
      ElMessage.warning(`答题未通过，得分：${score}，请再接再厉`)
    }

    joinDialogVisible.value = false
    loadActivityDetail()
  } catch (error) {
    ElMessage.error('提交答案失败')
  }
}

const calculateQuizScore = () => {
  let correctCount = 0
  quizAnswers.value.forEach((answer, index) => {
    if (answer === quizQuestions.value[index].answer) {
      correctCount++
    }
  })
  return Math.round((correctCount / quizQuestions.value.length) * 100)
}

// 日期选择限制
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

const disabledHours = () => {
  const hours = []
  for (let i = 0; i < 24; i++) {
    if (i < 9 || i > 17) {
      hours.push(i)
    }
  }
  return hours
}

onMounted(() => {
  loadActivityDetail()
})
</script>

<style lang="scss" scoped>
.activity-detail {
  padding: 20px;

  .detail-card {
    .activity-header {
      display: flex;
      gap: 20px;
      margin-bottom: 30px;

      .activity-image {
        width: 400px;
        height: 300px;
        border-radius: 4px;
      }

      .activity-info {
        flex: 1;

        h1 {
          margin: 0 0 20px;
          font-size: 24px;
          color: #303133;
        }

        .activity-meta {
          margin-bottom: 20px;

          p {
            display: flex;
            align-items: center;
            gap: 5px;
            margin: 10px 0;
            color: #909399;
            font-size: 14px;
          }
        }

        .activity-tags {
          .el-tag {
            margin-right: 10px;
          }
        }
      }
    }

    .activity-content,
    .activity-rules,
    .activity-process {
      margin-bottom: 30px;

      h2 {
        margin: 0 0 20px;
        font-size: 20px;
        color: #303133;
      }
    }

    .content-text {
      line-height: 1.8;
      color: #606266;
    }

    .rules-list {
      .rule-item {
        display: flex;
        align-items: flex-start;
        gap: 10px;
        margin-bottom: 10px;
        color: #606266;

        .el-icon {
          color: #409EFF;
          margin-top: 4px;
        }
      }
    }

    .activity-actions {
      display: flex;
      justify-content: center;
      margin-top: 30px;
    }
  }
}

.quiz-container {
  .question-item {
    margin-bottom: 20px;

    h3 {
      margin: 0 0 10px;
      font-size: 16px;
      color: #303133;
    }

    .el-radio-group {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }
  }

  .quiz-actions {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}
</style> 